﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;

namespace OpenRAMS
{
    public partial class index : System.Web.UI.Page
    {
        String dbInString;

        protected void Page_Load(object sender, EventArgs e)
        {
            try { dbInString = ConfigurationManager.ConnectionStrings["default"].ConnectionString; }
            catch { dbInString = ""; }
        }

        protected void btnLogin_Click(Object sender, EventArgs e)
        {
            //Setup DB connection & build query
            SqlConnection dbConnection = new SqlConnection(dbInString);
            SqlCommand dbCommand = dbConnection.CreateCommand();
            dbCommand.CommandText = "SELECT txtRoles FROM tblUsers WHERE txtUserName=@username AND txtPassword=@password";

            //Set parameters
            dbCommand.Parameters.Add("@username", SqlDbType.VarChar, 20).Value = Username.Value;
            dbCommand.Parameters.Add("@password", SqlDbType.VarChar, 30).Value = Password.Value;

            //run DB command
            dbConnection.Open();
            SqlDataReader dbReader = dbCommand.ExecuteReader();

            if (dbReader.Read())
            {
                //Create authentication ticket. Stores a cookie that expires within 30 minutes
                FormsAuthenticationTicket fTicket = new FormsAuthenticationTicket(1, Username.Value, DateTime.Now, DateTime.Now.AddMinutes(30), true, dbReader.GetString(0), FormsAuthentication.FormsCookiePath);
                String test = dbReader.GetString(0);
                string fTicketHash = FormsAuthentication.Encrypt(fTicket);  //being a good citizen, OpenRAMS encrypts its cookies

                //Setup login cookie and add to HTTP response
                HttpCookie fTicketCookie = new HttpCookie(FormsAuthentication.FormsCookieName, fTicketHash);
                if (fTicket.IsPersistent) fTicketCookie.Expires = fTicket.Expiration;
                Response.Cookies.Add(fTicketCookie);

                //redirect to request URL, else home
                string retUrl = Request.QueryString["ReturnUrl"];
                if (retUrl == null) retUrl = "/";
                Response.Redirect(retUrl);
            }
            else
            {
                lblError.Text = "Either username or password are incorrect. Please try again.";
                lblError.Visible = true;
            }
            dbReader.Close();
            dbConnection.Close();
        }
    }
}